#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文档解析器主模块
提供统一的文档解析接口，支持Word和PDF。
"""
import json
import os
import sys
from typing import Dict, Any
import logging

logging.basicConfig(level=logging.INFO, filename='parse_log.txt')

from parser.doc_parser import DocParser
from parser.pdf_parser import PdfParser

def parse_document(file_path: str) -> Dict[str, Any]:
    ext = os.path.splitext(file_path)[1].lower()
    if ext == '.docx':
        parser = DocParser()
    elif ext == '.pdf':
        parser = PdfParser()
    else:
        logging.error(f"不支持的文件类型: {ext}")
        raise ValueError("不支持的文件类型")
    
    try:
        return parser.parse_document(file_path)
    except Exception as e:
        logging.error(f"解析 {file_path} 失败: {e}")
        # 尽力解析，返回部分
        return {"title": os.path.basename(file_path), "sections": [], "metadata": {"error": str(e)}}

def save_to_json(data: Dict[str, Any], output_path: str):
    try:
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        logging.info(f"JSON saved to {output_path}")
    except Exception as e:
        logging.error(f"Save failed: {e}")

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        file_path = sys.argv[1]
    else:
        file_path = "docs/CoFile外部校正说明书.docx"  # 示例
    data = parse_document(file_path)
    base_name = os.path.splitext(os.path.basename(file_path))[0]
    output_path = f"result/{base_name}json.json"
    save_to_json(data, output_path)
    print(f"Parsed and saved to {output_path}")
